// 导入路由模块下的静态路由表
import { constantRoutes, asyncRoutes } from '@/router/index'

// 路由数组(响应式动态数据)
const state = () => {
  return {
    // 路由表：默认值是静态路由表的值
    routes: constantRoutes
  }
}

const mutations = {
  // 设置路由表
  setRoutes: (state, showAsuncRoutes) => {
    // 给routes数组追加筛选后的动态路由表
    // state.routes.push(...showAsuncRoutes)
    state.routes = [...constantRoutes, ...showAsuncRoutes]
  },
  // 清空路由表
  removeRoutes: (state) => {
    state.routes = []
  }
}

const actions = {
  // 筛选动态路由表
  filterAsyncRouteAction: ({ commit }, menus) => {
    // 基于动态路由表和menus数组筛选
    const showAsyncRoutes = asyncRoutes.filter((item) =>
      menus.includes(item.children[0].name)
    )
    // 筛选完毕之后提交mutation
    commit('setRoutes', showAsyncRoutes)
    // 返回筛选结果给路由前置守卫
    return showAsyncRoutes
  }
}

export default {
  // 开启命名空间，防止变量重名
  namespaced: true,
  // 变量名，简写
  state,
  mutations,
  actions
}
